
var attribution = new ol.Attribution({
    html: '南京海启'
});


var model;

var format = new ol.format.WKT();

/**
 * Currently drawn feature.
 * @type {ol.Feature}
 */
var sketch;


/**
 * The help tooltip element.
 * @type {Element}
 */
var helpTooltipElement;


/**
 * Overlay to show the help messages.
 * @type {ol.Overlay}
 */
var helpTooltip;


/**
 * The measure tooltip element.
 * @type {Element}
 */
var measureTooltipElement;


/**
 * Overlay to show the measurement.
 * @type {ol.Overlay}
 */
var measureTooltip;


/**
 * Message to show when the user is drawing a polygon.
 * @type {string}
 */
var continuePolygonMsg = '点击继续测面';


/**
 * Message to show when the user is drawing a line.
 * @type {string}
 */
var continueLineMsg = '点击继续测距';

//坐标系
var projection = ol.proj.get('EPSG:3857');
var projectionExtent = projection.getExtent();
var size = ol.extent.getWidth(projectionExtent) / 256;
var resolutions = new Array(18);
var matrixIds = new Array(18);
for (var z = 0; z < 18; ++z) {
    resolutions[z] = size / Math.pow(2, z);
    matrixIds[z] = z;
}

//水域
var waterSource= new ol.source.Vector({wrapX: false });
var waterArea=new ol.layer.Vector({
    source: waterSource,
    style: new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: 'blue',
            width: 2
        }),
    })
});

//报告线
var reportLineSource= new ol.source.Vector({wrapX: false });
var reportLine=new ol.layer.Vector({
    source: reportLineSource,
    style: new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: 'red',
            width: 2
        }),
    })
});

//server
var serverSource= new ol.source.Vector({wrapX: false });
var server=new ol.layer.Vector({
    title:"服务点",
    source: serverSource,
    style: new ol.style.Style({
        fill: new ol.style.Fill({
            color: 'red'
        }),
        stroke: new ol.style.Stroke({
            color: 'red',
            width: 2
        }),
        image: new ol.style.Circle({
            radius: 7,
            fill: new ol.style.Fill({
                color: 'red'
            }),
            stroke: new ol.style.Stroke({
                color: '#00FF00',
                width: 2
            })
        })
    })
});

//checkServer
var checkServerSource= new ol.source.Vector({wrapX: false });
var checkServer=new ol.layer.Vector({
    title:"服务点",
    source: checkServerSource,
    style: new ol.style.Style({
        fill: new ol.style.Fill({
            color: 'red'
        }),
        stroke: new ol.style.Stroke({
            color: 'red',
            width: 2
        }),
        image: new ol.style.Circle({
            radius: 7,
            fill: new ol.style.Fill({
                color: '#8624E5'
            }),
            stroke: new ol.style.Stroke({
                color: '#00FF00',
                width: 2
            })
        })
    })
});



//vts
var vtsSource= new ol.source.Vector({wrapX: false });
var vts=new ol.layer.Vector({
    source: vtsSource,
    style: new ol.style.Style({
        // fill: new ol.style.Fill({
        //     color: 'red'
        // }),
        stroke: new ol.style.Stroke({
            color: 'red',
            width: 2
        }),
        image: new ol.style.Circle({
            radius: 7,
            fill: new ol.style.Fill({
                color: 'red'
            }),
            stroke: new ol.style.Stroke({
                color: '#00FF00',
                width: 2
            })
        })
    })
});


//船舶图层
var shipSource = new ol.source.ImageWMS({
    ratio: 1,
    url: 'http://geo.zmsa.com.cn:8081/geoserver/cyx/wms',
    params: {
        'FORMAT': 'image/png',
        'VERSION': '1.1.1',
        STYLES: '',
        LAYERS: 'cyx:ais_ship',
    },
    serverType: 'geoserver'
    // imageLoadFunction: function(image, src) {
    //     image.getImage().src = src + "&t=" + new Date();
    // }
});

//泊位
var mtbwSource = new ol.source.ImageWMS({
    ratio: 1,
    url: 'http://geo.zmsa.com.cn:8081/geoserver/HQSHP/wms',
    params: {
        'FORMAT': 'image/png',
        'VERSION': '1.1.1',
        STYLES: '',
        LAYERS: 'HQSHP:MTBW',
    },
    serverType: 'geoserver'
    // imageLoadFunction: function(image, src) {
    //     image.getImage().src = src + "&t=" + new Date();
    // }
});

var layeroption={
    'FORMAT': 'image/png',
    'VERSION': '1.1.1',
    STYLES: '',
    LAYERS: 'cyx:mobile_ship',
    // CQL_FILTER:'company %27%27'
}

if(company){
    layeroption.CQL_FILTER = "company_id='"+company+"'";
}


var cyxSource = new ol.source.ImageWMS({
    ratio: 1,
    url: 'http://geo.zmsa.com.cn:8081/geoserver/cyx/wms',
    params: layeroption,
    serverType: 'geoserver'
    // imageLoadFunction: function(image, src) {
    //     image.getImage().src = src + "&t=" + new Date();
    // }
});

var sourceMeasure= new ol.source.Vector();
var vectorMeasure = new ol.layer.Vector({
    source: sourceMeasure,
    style: new ol.style.Style({
        fill: new ol.style.Fill({
            color: 'rgba(255, 255, 255, 0.2)'
        }),
        stroke: new ol.style.Stroke({
            color: '#ffcc33',
            width: 2
        }),
        image: new ol.style.Circle({
            radius: 7,
            fill: new ol.style.Fill({
                color: '#ffcc33'
            })
        })
    })
});

var mapArray=new Array();

var ais;

var mapObj;

var startIconStyle = new ol.style.Style({
    image:new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
        anchor: [0.5, 32],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        src: basePath+'/images/start.png',
        scale:1,
    }))
});


var endIconStyle = new ol.style.Style({
    image:new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
        anchor: [0.5, 32],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        src: basePath+'/images/end.png',
        scale:1
    }))
});

var aisImage=new ol.layer.Image({
    title: 'AIS船舶',
    source: shipSource,
    visible:false,
    // zIndex:1
})

var gpsImage=new ol.layer.Image({
    title: 'GPS船舶',
    source: cyxSource,
    visible:false,
    // zIndex:1
})

function initMap(target,mousePosition,container) {

    mapObj=new Object();
    mapObj.t;
    mapObj.redPosition;
    mapObj.trackShip=null;

    mapObj.target=target;
    mapObj.select= new ol.interaction.Select(
        {
            layers:[vector,vts,server,checkServer],
            style: new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: '#006BB3',
                    width: 2
                }),
                image: new ol.style.Circle({
                    radius: 7,
                    fill: new ol.style.Fill({
                        color: '#006BB3'
                    }),
                    stroke: new ol.style.Stroke({
                        color: 'white',
                        width: 2
                    })
                })
            })
        }
    );


    mapObj.measureTooltipElement = document.createElement('div');
    mapObj.measureTooltipElement.className = 'tooltip tooltip-static';
    mapObj.measureTooltip = new ol.Overlay({
        element:mapObj.measureTooltipElement,
        offset: [0, -5],
        positioning: 'bottom-center'
    });



    mapObj.overlay=new ol.Overlay(/** @type {olx.OverlayOptions} */ ({
        element: document.getElementById(container),
        autoPan: true,
        autoPanAnimation: {
            duration: 2500
        }
    }));

    //轨迹
    mapObj.trailSource = new ol.source.Vector({wrapX: false });

    //路线
    mapObj.startFeature;
    mapObj.endFeature;
    mapObj.startLonLat;
    mapObj.endLonLat;
    mapObj.pathSource = new ol.source.Vector({wrapX: false });

    //跟踪船舶icon
    mapObj.iconFeature = new ol.Feature({
        geometry: new ol.geom.Point(ol.proj.fromLonLat([118.7725, 32.1307])),
        population: 4000,
        rainfall: 500
    });



    mapObj.icon=new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
        anchor: [0.5, 32],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        src: basePath+'/images/ship.png',
        rotation:Math.PI/180*90,
        scale:0.5
    }))

    mapObj.iconStyle = new ol.style.Style({
        image:mapObj.icon
    });

    mapObj.iconSource = new ol.source.Vector({wrapX: false });
    mapObj.iconFeature.setStyle(mapObj.iconStyle);
    // mapObj.iconSource.addFeature(mapObj.iconFeature);
    mapObj.mousePosition=mousePosition;
    //鼠标位置
    mapObj.mousePositionControl = new ol.control.MousePosition({
        coordinateFormat: ol.coordinate.createStringXY(4),
        projection: 'EPSG:4326',
        className: 'custom-mouse-position',
        target: document.getElementById(mousePosition),
        undefinedHTML: '&nbsp;'
    });
    mapObj.bkSource=new ol.source.Vector({ wrapX: false });
    mapObj.view = new ol.View({
        projection: 'EPSG:3857',
        extent: [1000000, 1000000, 40000000, 10000000],
        center: ol.proj.fromLonLat([118.8348, 32.1648]),
        zoom: 13,
        minZoom: 4,
        maxZoom: 17
    });
    mapObj.layers=new ol.Collection();

    if(company)
    {
        mapObj.layers=[
            vector,
            aisImage,
            gpsImage,
            server
        ]
    }else {
        mapObj.layers=[
            aisImage,
            gpsImage,
            vector,
            waterArea,
            reportLine,
            vts,
            checkServer
        ]
    }

    mapObj.map = new ol.Map({
        target:mapObj.target,
        controls: ol.control.defaults({
            attribution: false
            // attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
            //     collapsible: true
            // })
        }).extend([
            mapObj.mousePositionControl,
            // new ol.control.FullScreen(),
        ]),
        interactions: ol.interaction.defaults().extend([
            new ol.interaction.DragRotateAndZoom(),
            mapObj.select
        ]),
        overlays:[mapObj.overlay,mapObj.measureTooltip],
        layers: [
            new ol.layer.Tile({
               opacity: 0.7,
               source: new ol.source.WMTS({
                   attributions: [attribution],
                   url: 'http://t' + GetRandomNum(0, 6) + '.tianditu.cn/vec_w/wmts',
                   layer: 'vec',
                   matrixSet: 'w',
                   format: 'tiles',
                   projection: projection,
                   tileGrid: new ol.tilegrid.WMTS({
                       origin: ol.extent.getTopLeft(projectionExtent),
                       resolutions: resolutions,
                       matrixIds: matrixIds
                   }),
                   STYLE: 'default',
                   wrapX: true
               })
            }),
            new ol.layer.Tile({
                visible: true,
                source: new ol.source.TileWMS({
                    url: 'http://geo.zmsa.com.cn:8081/geoserver/gwc/service/wms', //'http://geo.zmsa.com.cn:8081/geoserver/HQSHP/wms',
                    projection: 'EPSG:3857',
                    params: {
                        SERVICE: 'WMS',
                        FORMAT: 'image/png',
                        VERSION: '1.1.1',
                        tiled: true,
                        STYLES: '',
                        LAYERS: 'HQSHP:jiangsu'
                    }
                }),
                extent: [13180000, 3700000, 13510000, 3808000]
            }),
            new ol.layer.Group({
               title: '图层',
               layers:mapObj.layers
            }),
            new ol.layer.Vector({
               source:mapObj.bkSource,
               style: new ol.style.Style({
                   stroke: new ol.style.Stroke({
                       color: '#FF0000',
                       width: 2
                   })
               })
            }),
            new ol.layer.Vector({
                source:mapObj.trailSource ,
                style: new ol.style.Style({
                    stroke: new ol.style.Stroke({
                        color: '#FF0000',
                        width: 4
                    })
                })
            }),
            new ol.layer.Vector({
                source:mapObj.pathSource ,
                style: new ol.style.Style({
                    stroke: new ol.style.Stroke({
                        color: '#FF00FF',
                        width: 4
                    })
                })
            }),
            new ol.layer.Vector({
                source:mapObj.iconSource,
                style: new ol.style.Style({
                    stroke: new ol.style.Stroke({
                        color: '#FF0000',
                        width: 2
                    })
                })
            })
        ],
        view:  mapObj.view
    });
    if(target=="map1")
    {
        mapArray.unshift(mapObj);
        mapObj.map.addLayer(vectorMeasure);
    }else {
        mapArray.push(mapObj);
    }

    addEvent(mapObj);
    selected(mapObj.select,mapObj);
    // $("#"+target).append("<div class='ol-close-screen ol-unselectable ol-control'><button type='button'  onclick='removeMapByMapId(&quot;"+target+""+"&quot;)'>×</button></div>");

}


Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}



/**
 * Handle pointer move.
 * @param {ol.MapBrowserEvent} evt The event.
 */
var pointerMoveHandler = function(evt) {
    if (evt.dragging) {
        return;
    }
    /** @type {string} */
    var helpMsg = '点击开始测量';

    if (sketch) {
        var geom = (sketch.getGeometry());
        if (geom instanceof ol.geom.Polygon) {
            helpMsg = continuePolygonMsg;
        } else if (geom instanceof ol.geom.LineString) {
            helpMsg = continueLineMsg;
        }
    }

    helpTooltipElement.innerHTML = helpMsg;
    helpTooltip.setPosition(evt.coordinate);
    helpTooltipElement.classList.remove('hidden');
};


/**
 * Format length output.
 * @param {ol.geom.LineString} line The line.
 * @return {string} The formatted length.
 */
var formatLength = function(line) {
    var length;
    length = Math.round(line.getLength() * 100) / 100;
    var output;
    if (length > 100) {
        output = (Math.round(length / 1000 * 100) / 100) +
            ' ' + 'km';
    } else {
        output = (Math.round(length * 100) / 100) +
            ' ' + 'm';
    }
    return output;
};


/**
 * Format area output.
 * @param {ol.geom.Polygon} polygon The polygon.
 * @return {string} Formatted area.
 */
var formatArea = function(polygon) {
    var area;
    area = polygon.getArea();
    var output;
    if (area > 10000) {
        output = (Math.round(area / 1000000 * 100) / 100) +
            ' ' + 'km<sup>2</sup>';
    } else {
        output = (Math.round(area * 100) / 100) +
            ' ' + 'm<sup>2</sup>';
    }
    return output;
};

/**
 * Creates a new help tooltip
 */
function createHelpTooltip() {
    if (helpTooltipElement) {
        helpTooltipElement.parentNode.removeChild(helpTooltipElement);
    }
    helpTooltipElement = document.createElement('div');
    helpTooltipElement.className = 'tooltip hidden';
    helpTooltip = new ol.Overlay({
        element: helpTooltipElement,
        offset: [15, 0],
        positioning: 'center-left'
    });
    mapArray[0].map.addOverlay(helpTooltip);
}


/**
 * Creates a new measure tooltip
 */
function createMeasureTooltip(mapObj) {
    if (measureTooltipElement) {
        measureTooltipElement.parentNode.removeChild(measureTooltipElement);
    }
    measureTooltipElement = document.createElement('div');
    measureTooltipElement.className = 'tooltip tooltip-measure';
    measureTooltip = new ol.Overlay({
        element: measureTooltipElement,
        offset: [0, -15],
        positioning: 'bottom-center'
    });
    mapObj.map.addOverlay(measureTooltip);
}

var l;

function addMeasureInteraction() {
    var value = typeSelect;
    if (value !== 'None') {
        draw = new ol.interaction.Draw({
            source:  sourceMeasure,
            type: /** @type {ol.geom.GeometryType} */ (typeSelect),
            style: new ol.style.Style({
                fill: new ol.style.Fill({
                    color: 'rgba(255, 255, 255, 0.2)'
                }),
                stroke: new ol.style.Stroke({
                    color: 'rgba(0, 0, 0, 0.5)',
                    lineDash: [10, 10],
                    width: 2
                }),
                image: new ol.style.Circle({
                    radius: 5,
                    stroke: new ol.style.Stroke({
                        color: 'rgba(0, 0, 0, 0.7)'
                    }),
                    fill: new ol.style.Fill({
                        color: 'rgba(255, 255, 255, 0.2)'
                    })
                })
            })
        });
        mapArray[0].map.addInteraction(draw);
        l= mapArray[0].map.on('pointermove', pointerMoveHandler);
        mapArray[0].map.getViewport().addEventListener('mouseout', function() {
            helpTooltipElement.classList.add('hidden');
        });
        createMeasureTooltip(mapArray[0]);
        createHelpTooltip();
        var listener;
        draw.on('drawstart',
            function(evt) {
                // set sketch
                sketch = evt.feature;
                /** @type {ol.Coordinate|undefined} */
                var tooltipCoord = evt.coordinate;

                listener = sketch.getGeometry().on('change', function(evt) {
                    var geom = evt.target;
                    var output;
                    if (geom instanceof ol.geom.Polygon) {
                        output = formatArea(geom);
                        tooltipCoord = geom.getInteriorPoint().getCoordinates();
                    } else if (geom instanceof ol.geom.LineString) {
                        output = formatLength(geom);
                        tooltipCoord = geom.getLastCoordinate();
                    }
                    measureTooltipElement.innerHTML = output;
                    measureTooltip.setPosition(tooltipCoord);
                });
            }, this);
        draw.on('drawend',
            function(evt) {
                measureTooltipElement.className = 'tooltip tooltip-static';
                var closeElement = document.createElement("span");
                closeElement.className = "close";
                closeElement.innerHTML = "<i class='fa fa-close'></i>";
                closeElement.addEventListener('click', function() {
                    sourceMeasure.removeFeature(evt.feature);
                    closeElement.parentNode.style.display = 'none';
                }, false);
                measureTooltipElement.appendChild(closeElement)
                measureTooltip.setOffset([0, -7]);
                // unset sketch
                sketch = null;
                // unset tooltip so that a new one can be created
                measureTooltipElement = null;
                createMeasureTooltip(mapArray[0]);
                ol.Observable.unByKey(listener);
            }, this);
    }
}

var start = {
    elem: '#start',
    format: 'YYYY/MM/DD hh:mm:ss',
    min:  laydate.now(-20), //设定最小日期为当前日期
    max:  laydate.now(), //最大日期
    isclear: true,
    istime: true,
    istoday: false,
    choose: function(datas){
        // end.min = datas; //开始日选好后，重置结束日的最小日期
        var dateStart=new Date(datas);
        var dateEnd=new Date(datas);
          dateEnd.setDate(dateStart.getDate()+3);
        var endDate=new Date($('#end').val());
        endDate.setDate(endDate.getDate()-3);
        if(dateStart<endDate||dateStart>new Date($('#end').val()))
        {

            if(dateEnd>new Date())
            {
                $('#end').val(laydate.now());
            } else {
                $('#end').val(dateEnd.Format("yyyy/MM/dd hh:mm:ss"));
            }
        }
        // end.start = datas //将结束日的初始值设定为开始日
    }
};
var end = {
    elem: '#end',
    format: 'YYYY/MM/DD hh:mm:ss',
    min: laydate.now(-20),
    max: laydate.now(),
    isclear: true,
    istime: true,
    istoday: false,
    choose: function(datas){
        var dateStart=new Date(datas);
        var dateEnd=new Date(datas);
        dateStart.setDate(dateEnd.getDate()-3);


        var startDate=new Date($('#start').val());
        startDate.setDate(startDate.getDate()+3);

        if(dateEnd>startDate||dateEnd<new Date($('#start').val()))
        {

            if(dateStart<new Date(laydate.now(-20)))
            {
                $('#start').val(laydate.now(-20));
            } else {
                $('#start').val(dateStart.Format("yyyy/MM/dd hh:mm:ss"));
            }
        }
    }

};
function removeDuplicatedItem(ar) {
    var ret = [],
        end;
    ar.sort();
    end = ar[0];
    ret.push(ar[0]);
    for (var i = 1; i < ar.length; i++) {
        if (ar[i] != end) {
            ret.push(ar[i]);
            end = ar[i];
        }
    }
    return ret;
}

var trackCyx=new Array();
var trackAis=new Array();

var getAis = function() {
    clearTimeout(ais);
    ais = null;
    trackCyx=[];
    trackAis=[];
    //console.log(new Date().toLocaleString());
    //shipSource.setUrl('http://geo.zmsa.com.cn:8081/geoserver/cyx/wms?t=' + new Date())
    shipSource.updateParams({ 'TIME': new Date().toISOString() });
    cyxSource.updateParams({ 'TIME': new Date().toISOString() });

    for(var a=0;a<mapArray.length;a++)
    {
        if(mapArray[a].trackShip)
        {

            if(mapArray[a].trackShip.type=='cyx')
            {
                trackCyx.push(mapArray[a].trackShip.trackId);
            } else if(mapArray[a].trackShip.type=='ais')
            {
                trackAis.push(mapArray[a].trackShip.trackId);
            }
        }
    }

    if(trackCyx.length>0)
    {
        trackCyx=removeDuplicatedItem(trackCyx);
        var str=trackCyx[0];
        for(var a=1;a<trackCyx.length;a++)
        {
            str=str+","+trackCyx[a];
        }

        $.ajax({
            type:"POST",
            url: "/manage/ship/findByImei",
            data:{
                shipimei:str,
            },
            success:function (data) {
                for(var i=0;i<mapArray.length;i++)
                {

                    if(mapArray[i].trackShip)
                    {
                        for(var j=0;j<data.length;j++)
                        {

                            if(mapArray[i].trackShip.trackId==data[j].shipimei)
                            {

                                loc(mapArray[i],data[j].longitude,data[j].latitude,data[j].couese);
                                break;
                            }
                        }
                    }
                }
            }
        })
    }

    if(trackAis.length>0)
    {
        trackAis=removeDuplicatedItem(trackAis);
        var str=trackAis[0];
        for(var a=1;a<trackAis.length;a++)
        {
            str=str+","+trackAis[a];
        }

        $.ajax({
            type:"POST",
            url: "/manage/ship/user/findByMmsi",
            data:{
                mmsi:str,
            },
            success:function (data) {
                for(var i=0;i<mapArray.length;i++)
                {

                    if(mapArray[i].trackShip!=null)
                    {
                        for(var j=0;j<data.length;j++)
                        {
                            if(mapArray[i].trackShip.trackId==data[j].mmsi)
                            {
                                loc(mapArray[i],data[j].lon,data[j].lat,data[j].course);
                                break;
                            }
                        }
                    }
                }
            }
        })
    }
    ais = setTimeout(getAis, 5000);
};

var loadLayerIndex = -1;




function creatIcon(mabObj,lon,lat,course) {
    mabObj.iconSource.clear();
    if(course)
    {
        mabObj.iconFeature.setGeometry(new ol.geom.Point(ol.proj.fromLonLat([parseFloat(lon), parseFloat(lat)])));
        mabObj.icon.setRotation(Math.PI/180*course);
        mabObj.iconSource.addFeature(mabObj.iconFeature);
    }

}



var editFeatureVts = function (feature,mapObj) {
    var ft = feature.getGeometry().getType();
    var info = "<tr><td class='tdl'>标题</td><td class='tdr'><input style='width:300px;' id='txtTitle' type='text' /></td></tr>";
    info += " <tr><td class='tdl'>内容</td><td class='tdr'><textarea style='width:300px;' id='txtContent' rows='5' ></textarea></td></tr>";
    info += " <tr><td class='tdl'>触发事件</td><td class='tdr'><select id='_event'><option value='1'>靠近</option>" + (ft == "Polygon" ? "<option value='2'>进入</option>" : "") + "</select></td></tr>";

    var ml = layer.open({
        id: 'addWarn',
        area: ['450px'],
        type: 1,
        closeBtn: 0,
        title: ["查看VTS警告", 'font-size:18px; font-weight:bold'],
        content: "<table class='detail'>" + info + "</table>",
        btn: ["关闭","无效","删除"],
        success: function () {
            $("#txtTitle").val(feature.get('Title'));
            $("#txtContent").val(feature.get('Content'));
            $("#_event").val(feature.get('Event'));
        },
        yes: function (index) {
            layer.close(ml);

        },
        btn2:function(){
            $.ajax({
                type:'post',
                url:'/manage/map/setAlert',
                data:{guid:feature.getId(),state:'0'},
                dataType: "json",
                success:function(data){
                    if(data){
                        vtsSource.removeFeature(feature);
                    }
                }
            });
        },
        btn3:function(){
            $.ajax({
                type:'post',
                url:'/manage/map/dropAlert',
                data:{guid:feature.getId()},
                dataType: "json",
                success:function(data){
                    if(data){
                        vtsSource.removeFeature(feature);
                    }
                }
            });
        },
        end:function () {
        mapObj.select.getFeatures().clear();
    }
    })
}

function change() {
    if ($('#_event').val() == '1') {
        $('#distance').show();
    } else {
        $('#distance').hide();
    }
}

function editServer(feature,mapObj) {
    var ft = feature.getGeometry().getType();
    if(feature.get('source')=='warning'){
        var info = "<tr><td class='tdl'>标题</td><td class='tdr'><input style='width:300px;' id='txtTitle' type='text' /></td></tr>";
        info += " <tr><td class='tdl'>内容</td><td class='tdr'><textarea style='width:300px;' id='txtContent' rows='5' ></textarea></td></tr>";
        info += " <tr><td class='tdl'>触发事件</td><td class='tdr'><select id='_event' onchange='change()'><option value='1'>靠近</option>" +(ft=="Polygon" ?"<option value='2'>进入</option>" : "") + "</select><input style='width: 100px;height: 20px' id='distance' type='number'  value='500'/></td></tr>";
        var guid = "";
        var btn = ['保存', '取消'];
        if (feature.values_ && feature.values_.guid) {
            guid = feature.values_.guid;
            btn = ['保存', '取消', '删除'];
        }
        var ml = layer.open({
            id: 'addWarn',
            area: ['450px'],
            type: 1,
            closeBtn: 0,
            title: ["保存警告", 'font-size:18px; font-weight:bold'],
            content: "<table class='detail'>" + info + "</table>",
            btn: btn,
            success: function () {
                if (guid && guid != "") {
                    $("#txtTitle").val(feature.values_.title);
                    $("#txtContent").val(feature.values_.contents);
                    $("#_event").val(feature.values_.event);
                    $("#distance").val(feature.values_.distance);
                    if( $("#_event").val()=='2')
                    {
                        $("#distance").hide();
                    }


                }
            },
            end:function () {
                mapObj.select.getFeatures().clear();
            },
            yes: function (index) {
                var title = $("#txtTitle").val();
                var content = $("#txtContent").val();
                var _event = $("#_event").val();
                var distance=$("#distance").val();
                if(_event=='2')
                {
                    distance=null;
                }

                if (title == "" || content == "") {
                    layer.msg("标题和内容不能为空");
                }
                else {
                    var prop = {
                        guid: guid,
                        title: title,
                        contents: content,
                        wkt: serialize1(feature),
                        warningtype: ft,
                        event: _event,
                        mark: "",
                        distance:distance
                    }

                    var url;
                    if(!company)
                    {
                        url="/manage/map/navigat/warning/save";
                    }else {
                        url="/manage/map/company/warning/save"
                    }
                    feature.setProperties(prop);
                    $.ajax({
                        type: "POST",
                        url:url,
                        data: prop,
                        dataType: "json",
                        success: function (data) {
                            if (data.result == true) {
                                feature.values_.guid = data.guid;
                                feature.id = data.guid;
                                source.clear();
                                layer.close(ml);
                                layer.msg("保存成功");
                                if(!company) {
                                    getFeature();
                                }else {
                                    getCompanyWarning();
                                }
                            }
                            else {
                                layer.msg("保存失败");
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            console.log(errorThrown);
                        }
                    });
                }
            },
            btn2: function (index) {
                if (guid == "") {
                    source.removeFeature(feature);
                }
            },
            btn3: function (index) {
                layer.confirm('确定删除?', {icon: 3, title: '提示'}, function (index) {
                    var url;
                    if(!company)
                    {
                        url="/manage/map/navigat/warning/delete";
                    }else {
                        url="/manage/map/company/warning/delete";
                    }
                    $.ajax({
                        type: "POST",
                        url: url,
                        data: {guid: guid, action: "d"},
                        dataType: "json",
                        success: function (data) {
                            if (data.result == true) {
                                source.removeFeature(feature);
                                layer.msg("删除成功");
                                layer.close(ml);
                            }
                            else {
                                layer.msg("删除失败");
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            console.log(errorThrown);
                        }
                    });
                });
            }
        })
    }else{
        var info="";
        var id = "";
        var ml;
        var title;
        if (feature.values_ && feature.values_.id) {
            id = feature.values_.id;
        }
        if(ft=='Point') {
            $.ajax({
                type: "POST",
                url: "/manage/map/server-point/ajax/getById",
                data: {id: id},
                dataType: "json",
                success: function (data) {
                    if (data) {
                        var status;
                        if(data.type=='0')
                        {
                            status='待审核';
                        }else {
                            status='已审核';
                        }
                        btn = [];
                        title = ["服务点信息", 'font-size:18px; font-weight:bold'];
                        info = "<tr><td class='tdl'>名称</td><td class='tdr'>" + data.name + "</td></tr>";
                        info += "<tr><td class='tdl'>经纬度</td><td class='tdr'>" + ol.coordinate.toStringHDMS(ol.proj.toLonLat(feature.getGeometry().flatCoordinates)) + "</td></tr>";
                        info += "<tr><td class='tdl'>服务类型</td><td class='tdr'>" + data.serverType + "</td></tr>";
                        info += "<tr><td class='tdl'>发布者</td><td class='tdr'>" +data.companyName+ "</td></tr>";
                        info += "<tr><td class='tdl'>发布时间</td><td class='tdr'>" +data.publishtime+ "</td></tr>";
                        info += "<tr><td class='tdl'>服务内容</td><td class='tdr' style='word-break: break-all;width: 200px'>" + data.message + "</td></tr>";

                        if(!company)
                        {
                            info += "<tr><td class='tdl'>状态</td><td class='tdr'>" +status+ "</td></tr>";
                        }
                    }
                    ml = layer.open({
                        type: 1,
                        skin: 'layui-layer-rim', //加上边框
                        area: ['300px'], //宽高
                        closeBtn: 1,
                        title: title,
                        content: "<table class='detail'>" + info + "</table>",
                        success: function () {
                        },
                        cancel: function () {
                            if (id == "") {
                                source.removeFeature(feature);
                            }
                        },
                        end: function () {
                            mapObj.select.getFeatures().clear();
                        }
                    });


                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log(errorThrown);
                }
            });
        }
    }
}

function drawEnd(draw,mapObj) {

    draw.on('drawend',function (evt) {

       evt.feature.set("source","warning");
       editServer(evt.feature,mapObj);
    })
}



function selected(select,mapObj) {
    select.on('select',function (evt) {
        if(evt.selected[0])
        {
            if(evt.selected[0].get("source")=='vts')
            {
                hidePop(mapArray[0]);
                editFeatureVts(evt.selected[0],mapObj);
            }else {
                editServer(evt.selected[0],mapObj);
            }
        }


    })
}


function addEvent(mapObj) {
  mapObj.listener=mapObj.map.on('singleclick', function(evt) {

        showLoad();
        var coordinate = new ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326');
        var gpsUrl='';
        var aisUrl='';
        var mtbwUrl=mtbwSource.getGetFeatureInfoUrl(evt.coordinate, mapObj.view.getResolution(), mapObj.view.getProjection(), { 'INFO_FORMAT': 'application/json', 'FEATURE_COUNT': 10});
        var features=[];
        if(gpsImage.getVisible()){
            gpsUrl=cyxSource.getGetFeatureInfoUrl(evt.coordinate, mapObj.view.getResolution(), mapObj.view.getProjection(), { 'INFO_FORMAT': 'application/json', 'FEATURE_COUNT': 10});
            if(aisImage.getVisible())
            {
                aisUrl=shipSource.getGetFeatureInfoUrl(evt.coordinate, mapObj.view.getResolution(), mapObj.view.getProjection(), { 'INFO_FORMAT': 'application/json', 'FEATURE_COUNT': 10});
            }
        } else
        {
            if(aisImage.getVisible())
            {
                aisUrl= shipSource.getGetFeatureInfoUrl(evt.coordinate, mapObj.view.getResolution(), mapObj.view.getProjection(), { 'INFO_FORMAT': 'application/json', 'FEATURE_COUNT': 10});
            }
        }

      if(model=='start')
      {

          $("#endInput").val(ol.coordinate.toStringHDMS(mapObj.endLonLat));

          if(mapObj.startFeature)
          {
              mapObj.pathSource.removeFeature(mapObj.startFeature);
          }
          mapObj.startFeature=new ol.Feature({
          geometry: new ol.geom.Point(evt.coordinate),
          population: 4000,
          rainfall: 500
          });
          mapObj.startFeature.setStyle(startIconStyle);
          mapObj.startLonLat=coordinate;
          mapObj.pathSource.addFeature(mapObj.startFeature);
          $("#startInput").val(ol.coordinate.toStringHDMS(coordinate));
          if($("#endInput").val()==''||$("#endInput").val()==null)
          {
              $("#endInput")[0].focus();
          }

      }else if(model=='end')
      {
          console.log(mapObj.startLonLat);
          $("#startInput").val(ol.coordinate.toStringHDMS(mapObj.startLonLat));
          if(mapObj.endFeature)
          {
              mapObj.pathSource.removeFeature(mapObj.endFeature);
          }
          mapObj.endFeature=new ol.Feature({
              geometry: new ol.geom.Point(evt.coordinate),
              population: 4000,
              rainfall: 500
          });
          mapObj.endFeature.setStyle(endIconStyle);
          mapObj.endLonLat=coordinate;
          mapObj.pathSource.addFeature(mapObj.endFeature);
          $("#endInput").val(ol.coordinate.toStringHDMS(coordinate));
          if($("#startInput").val()==''||$("#endInput").val()==null)
          {
              $("#startInput")[0].focus();
          }
      }


      if(mapObj.startLonLat&&mapObj.endLonLat)
      {
          $.ajax({
              type: "POST",
              url: 'http://cloud.zmsa.com.cn:8081/net/ashx/GetNavRoute.ashx',
              data:{
                  x1:mapObj.startLonLat[0],
                  y1:mapObj.startLonLat[1],
                  x2:mapObj.endLonLat[0],
                  y2:mapObj.endLonLat[1],
                  dir:$('#dir').val()
              },
              async:false,
              dataType: "json",
              success: function (data) {
                  if(mapObj.pathFeature)
                  {
                      mapObj.pathSource.removeFeature(mapObj.pathFeature);
                  }
                  console.log(data.list);
                  var ff = new ol.format.WKT();
                  if(data.list[0].st_astext)
                  {
                      mapObj.pathFeature = ff.readFeature(data.list[0].st_astext,{
                          dataProjection: 'EPSG:4326',
                          featureProjection: 'EPSG:3857'
                      });
                      mapObj.pathSource.addFeature(mapObj.pathFeature);
                      mapObj.measureTooltipElement.style.display = 'block';
                      var content;
                      if(data.list[0].agg_cost<1000)
                      {
                          content=data.list[0].agg_cost.toFixed(1)+'m';
                      }else {
                          content=(data.list[0].agg_cost/1000).toFixed(3)+'km';
                      }

                    var endPoint= ff.readFeature(data.list[4].st_astext,{
                          dataProjection: 'EPSG:4326',
                          featureProjection: 'EPSG:3857'
                      });

                      mapObj.measureTooltipElement.innerHTML = content;
                      mapObj.measureTooltip.setPosition(endPoint.getGeometry().flatCoordinates);

                  }else {
                      mapObj.pathFeature=null;
                      mapObj.measureTooltipElement.style.display = 'none';
                      layer.msg("无航线");
                  }


              },
              error: function (XMLHttpRequest, textStatus, errorThrown) {
                  console.log(errorThrown);
              }
          });
      }


      if(gpsUrl!='')
      {
          $.ajax({
              type: "POST",
              url: gpsUrl,
              async:false,
              dataType: "json",
              success: function (data) {
                  closeLoad();
                  if (data) {
                      for(var i=0;i<data.features.length;i++)
                      {
                          features.push(data.features[i])
                      }
                  }
              },
              error: function (XMLHttpRequest, textStatus, errorThrown) {
                  closeLoad();
                  console.log(errorThrown);
              }
          });
      }

        if(aisUrl!='')
        {
            $.ajax({
                type: "POST",
                url: aisUrl,
                dataType: "json",
                async:false,
                success: function (data) {
                    closeLoad();
                    if (data) {
                        for(var i=0;i<data.features.length;i++)
                        {
                            features.push(data.features[i])
                        }
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    closeLoad();
                    console.log(errorThrown);
                }
            });
        }


        if(features.length>0)
        {
            showWMSInfo(features,mapObj);
        }

      $.ajax({
          type: "POST",
          url: mtbwUrl,
          dataType: "json",
          success: function (data) {
              closeLoad();
              if (data) {
                  if(data.features.length==1)
                  {
                      showQuayInfo(data.features[0]);
                  }
              }
          },
          error: function (XMLHttpRequest, textStatus, errorThrown) {
              closeLoad();
              console.log(errorThrown);
          }
      });
    });

    mapObj.view.on('change:resolution', function(evt) {
        //比例缩放事件
        if(mapObj.redPosition)
        {
            createRed(mapObj.redPosition,mapObj);
        }
    });
}


var showQuayInfo=function (feature) {
    var prop = feature.properties;
    var info = "";
    var QC = (prop.QC == null ? "暂无" : prop.QC);
    var lonlat='';
    if(prop.ZXJD&&prop.ZXJD!=''&&prop.ZXWD&&prop.ZXWD!='')
    {
        lonlat=[prop.ZXJD,prop.ZXWD];
    }

    var  wxp = (prop.WXP == 1 ? "危险品码头" : "一般码头");
    var title=[QC+"("+wxp+")", 'font-size:18px; font-weight:bold'];
    info += "<tr><td class='tdl' style='width: 80px'>所在辖区</td><td class='tdr'>" + prop.SZXQ+ "</td></tr>";
    info += "<tr><td class='tdl'>经纬度</td><td class='tdr'>" + lonlat+ "</td></tr>";
    info += "<tr><td class='tdl'>码头形式</td><td class='tdr'>" + prop.MTXS+ "</td></tr>";
    info += "<tr><td class='tdl'>开放类型</td><td class='tdr'>" + prop.KFLX+"</td></tr>";
    info += "<tr><td class='tdl'>SZWG</td><td class='tdr'>" + prop.SZWG + "</td></tr>";
    info += "<tr><td class='tdl'>建成日期</td><td class='tdr'>" + prop.JCRQ + "</td></tr>";

    layer.open({
        id: 'showQuay',
        type: 1,
        area: '500px',
        closeBtn: 1,
        title: title,
        content: "<table class='detail'>" + info + "</table>"
    })
}

var showWMSInfo = function(features,mapObj) {
    if (features.length > 0) {
        if (features.length == 1) {
            showInfo(features[0],mapObj);
        } else {
            showFeaturesList(features,mapObj);
        }
    }
}

var showFeaturesList = function(features,mapObj) {
    var s = "";
    for (var i = 0; i < features.length; i++) {
        var prop = features[i].properties;
        if (prop.guid)
            s += "<div class='d_block' style='background:#95cbf3' fid='" + i + "'>" + (prop.shipname == null ? "船名未设置" : prop.shipname) + "(" + prop.mmsi + ")</div>";
        else
            s += "<div class='d_block' fid='" + i + "'>" + (prop.shipname == null ? "" : prop.shipname) + "(" + prop.mmsi + ")</div>";

    }


    var lindex = -2;
    if (s.trim() != "") {
        lindex = layer.open({
            id: 'showdiv',
            type: 1,
            area: '300px',
            closeBtn: 1,
            title: ["请选择船舶", 'font-size:18px; font-weight:bold'],
            content: "<div class='detail'>" + s + "</div>"
        });
    }

    $('.d_block').click(function(e) {
        var fid = $(this).attr('fid');
        layer.close(lindex);
        showInfo(features[fid],mapObj);

    });
}

var showInfo = function(feature,mapObj) {
    var prop = feature.properties;
    var btn = [];
    var info = "";
    var plonlat = [parseFloat(prop.lon), parseFloat(prop.lat)];
    var shipname = (prop.shipname == null ? "暂无" : prop.shipname);
    var shipid = (prop.shipid == null ? "" : prop.shipid);
    var iemi = (prop.shipimei == null ? "" : prop.shipimei);
    var speed= (prop.speed*1.852).toFixed(3);

    info += "<tr><td class='tdl'>经纬度</td><td class='tdr'>" + ol.coordinate.toStringHDMS(plonlat) + "</td></tr>";
    //info += "<tr><td class='tdl'>纬度</td><td class='tdr'>" + SetHMS(prop.lat) + "</td></tr>";
    info += "<tr><td class='tdl'>速度</td><td class='tdr'>" + prop.speed +"节/"+speed+ "千米每小时</td></tr>";
    info += "<tr><td class='tdl'>航向</td><td class='tdr'>" + prop.course + "</td></tr>";
    info += "<tr><td class='tdl'>时间</td><td class='tdr'>" + new Date(prop.postime).toLocaleString() + "</td></tr>";
    
    var title=[shipname, 'font-size:18px; font-weight:bold'];
    if (prop.guid) {
        if(mapType=="one")
        {
            btn = ['发送信息','轨迹跟踪'];
        }else {
            btn = ['发送信息'];
        }

        $.ajax({
            type: "POST",
            url:  "/manage/map/server/ajax/shipServer/list",
            data: {guid:prop.guid,status:'1'},
            async:false,
            dataType: "json",
            success: function (data) {
                if(data[0])
                {
                    title=[shipname+'(服务船舶)', 'font-size:18px; font-weight:bold'];
                    info= "<tr><td class='tdl'>MMSI</td><td class='tdr'>" + prop.mmsi + "</td></tr>"+info;
                    info += "<tr><td class='tdl'>服务类型</td><td class='tdr'>" + data[0].serverType + "</td></tr>";
                    info += "<tr><td class='tdl'>服务内容</td><td class='tdr' style='word-break: break-all;width: 300px'>" + data[0].message + "</td></tr>";
                }
            }
        })
    } else {
        info= "<tr><td class='tdl'>MMSI</td><td class='tdr'>" + prop.mmsi + "<span onclick='focusShip(\""+shipname+"\",\""+prop.mmsi+"\")' style='font-size:24px; font-weight:bold;float: right;margin-right: 10px;cursor: pointer' title='关注'>+</span></td></tr>"+info;
    }
  var layerInfo=layer.open({
        id: 'showdiv2',
        type: 1,
        area: '500px',
        closeBtn: 1,
        title: title,
        content: "<table class='detail'>" + info + "</table>",
      success:function () {

      },
        end: function() {
            if(mapObj.trackShip==null)
            {
                mapObj.bkSource.clear();
                mapObj.redPosition=null;
            }
        },
        btn: btn,
        // yes: function(index, layero) {
        //
        //         if(company){
        //             showhtml(basePath+'/manage/map/company/voyage?shipid='+shipid, shipname+"航次报告");
        //         }else{
        //             showhtml(basePath+'/manage/map/voyage?shipid='+shipid, shipname+"航次报告");
        //         }
        //
        // },
        // btn2: function(index, layero) {
        //     if(company){
        //         showhtml(basePath+'/manage/map/company/accident?shipid='+shipid, shipname+"险情报告");
        //     }else{
        //         showhtml(basePath+'/manage/map/accident?shipid='+shipid, shipname+"险情报告");
        //     }
        //     return false;
        // },
        yes: function(index, layero) {
            sendMessage(shipid,shipname);
        },
        btn2: function() {
            var content = "</tr><td class='tdl'>起始时间</td><td class='tdr'><input type='text' style='width:150px'  class='laydate-icon'  onclick='laydate(start)' id='start'></td> "
            content += "</tr><td class='tdl'>结束时间</td><td class='tdr'><input type='text' style='width:150px' class='laydate-icon' onclick='laydate(end)' id='end'></td>"
            var trail = layer.open({
                type: 1,
                area: '300px',
                closeBtn: 1,
                title: ["查询轨迹", 'font-size:18px; font-weight:bold'],
                content: "<table class='detail'>" + content + "</table>",
                btn: ['确定', '取消'],
                success:function () {
                    var initDate=new Date();
                    $("#end").val(initDate.Format("yyyy/MM/dd hh:mm:ss"));
                    initDate.setDate(initDate.getDate()-3);
                    $("#start").val(initDate.Format("yyyy/MM/dd hh:mm:ss"));
                },
                yes: function () {
                    var start = $("#start").val();
                    var end = $("#end").val();
                    var startDate= new Date(start);
                    var endDate=new Date(end);

                    if(startDate>endDate)
                    {
                        layer.msg("结束时间不能小于开始时间");
                    }else {
                        endDate.setDate(endDate.getDate()-3);
                        if(startDate<endDate)
                        {
                            layer.msg("查询范围必须在3天内");
                        }else {
                            layer.close(trail);
                            layer.close(layerInfo);
                            layer.close(trails);
                            showTrail(basePath + "ship/guanzhu/trail?iemi=" + iemi + "&start=" + start + "&end=" + end, shipname + ":轨迹追踪", mapObj);
                        }
                    }
                },
                btn2: function () {

                }
            })
            return false;
        }
    });
    
    var coordinate = new ol.proj.transform(plonlat, 'EPSG:4326', 'EPSG:3857');
    createRed(coordinate,mapObj);
}



function getGZ(){
    var str = "<option value=''>--请选择分组--</option>";
    $.ajax({
        type: "POST",
        async:false,
        url: "/ship/guanzhu/ajax/groupList",
        data: {},
        dataType: "json",
        success: function (data) {
            for (var i = 0; i < data.length; i++) {
                str = str + "<option value='" + data[i].id + "'>" + data[i].name + "</option>";
            }
        }
    });
    return str;
}

var focusShip= function(shipname,mmsi) {
    var gz=getGZ();
    var content="<div style='margin:10px 0 0 10px'><span style='font-size: 14px'>船名:&nbsp;"+shipname+"</span></div>" +
        "<div style='margin:10px 0 0 10px'><span style='font-size: 14px'>MMSI:&nbsp;"+mmsi+"</span></div>" +
        "<div  style='margin: 10px 0 0 10px'><label for='guanid' style='font-size: 14px'>分组:</label>&nbsp;<select id='guanid'>"+gz+"</select></div>";
    var l=layer.open({
        type: 1,
        title: '添加关注',
        shadeClose: false,
        shade: 0.5,
        area: ['250px','200px'],
        content:content,
        btn:['关注','取消'],
        yes:function () {
            var id=$("#guanid").val();
            if(id=='')
            {
                layer.msg("请选择组别！");
            }else {
                $.ajax({
                    type: "POST",
                    url: "/manage/ship/user/addship",
                    data: {mmsi:mmsi ,id:id,name:shipname},
                    dataType: "json",
                    success: function (data) {
                        if(data.result == true){
                            layer.close(l);
                            layer.msg("添加成功！");
                        }else{
                            layer.msg("您已关注该船舶！");
                        }
                    }
                });
            }


        },
        btn2:function () {

        },
        end:function () {

        }
    })
}



function showLoad() {
    loadLayerIndex = layer.load(0, { time: 5 * 1000 });
}

function closeLoad() {
    layer.close(loadLayerIndex);
}

/**
 * 获取VTS告警信息
 */
var getVtsFeature = function () {
    var ff = new ol.format.WKT();
    $.ajax({
        type: "POST",
        url: basePath + "manage/map/alertList",
        data: {},
        dataType: "json",
        success: function (data) {
            var ffs = []; //
            for (i = 0; i < data.list.length; i++) {
                var f = ff.readFeature(data.list[i].Geom,{
                    dataProjection: 'EPSG:4326',
                    featureProjection: 'EPSG:3857'
                });
                var pp = data.list[i];
                f.setProperties(pp);
                f.setId(pp.Guid);
                f.set("source","vts");
                ffs.push(f);
                vtsSource.addFeature(f);
            }

        }
    })
}

var getFeature = function () {
    var ff = new ol.format.WKT();
    $.ajax({
        type: "POST",
        url: "/manage/map/navigat/warning/ajax/data/list",
        data: {},
        dataType: "json",
        success: function (data) {
            var ffs = [];
            for (var i= 0; i < data.length; i++) {
                var f = ff.readFeature(data[i].wkt,{
                    dataProjection: 'EPSG:4326',
                    featureProjection: 'EPSG:3857'
                });
                var pp = data[i];
                f.setProperties(pp);
                f.set("source","warning");
                f.setId(pp.guid);
                source.addFeature(f);
            }


        }
    })
}

var getServerPoint = function () {
    var ff = new ol.format.WKT();
    $.ajax({
        type: "POST",
        url: "/manage/map/server-point/ajax/data/list",
        data: {status:1},
        dataType: "json",
        success: function (data) {
            var ffs = [];
            for (var i= 0; i < data.length; i++) {
                var f = ff.readFeature(data[i].wkt,{
                    dataProjection: 'EPSG:4326',
                    featureProjection: 'EPSG:3857'
                });
                var pp = data[i];
                f.setProperties(pp);
                f.set("source","serverPoint");
                f.setId(pp.id);
                ffs.push(f);
            }
            serverSource.addFeatures(ffs);
        }
    })
}


var getCheckServerPoint = function () {
    var ff = new ol.format.WKT();
    $.ajax({
        type: "POST",
        url: "/manage/map/server-point/ajax/check",
        data: {},
        dataType: "json",
        success: function (data) {
            var ffs = [];
            for (var i= 0; i < data.length; i++) {
                var f = ff.readFeature(data[i].wkt,{
                    dataProjection: 'EPSG:4326',
                    featureProjection: 'EPSG:3857'
                });
                var pp = data[i];
                f.setProperties(pp);
                f.set("source","serverPoint");
                f.setId(pp.id);
                ffs.push(f);
            }
            checkServerSource.addFeatures(ffs);
        }
    })
}


var getCompanyWarning= function () {
    var ff = new ol.format.WKT();
    $.ajax({
        type: "POST",
        url: "/manage/map/company/warning/ajax/data/list",
        data: {},
        dataType: "json",
        success: function (data) {
            var ffs = [];
            for (var i= 0; i < data.length; i++) {
                var f = ff.readFeature(data[i].wkt,{
                    dataProjection: 'EPSG:4326',
                    featureProjection: 'EPSG:3857'
                });
                var pp = data[i];
                f.setProperties(pp);
                f.set("source","warning");
                f.setId(pp.guid);
                ffs.push(f);
            }
            source.addFeatures(ffs);
        }
    })
}

var showhtml = function (url, title) {
    layer.open({
        id: 'showcontent',
        area: ['970px', '440px'],
        type: 2,
        closeBtn: 1,
        title: [title, 'font-size:18px; font-weight:bold'],
        content: url

    })
}

var trails;

var showTrail = function (url, title,mapObj) {
   trails=layer.open({
        area: ['200px', '400px'],
        type: 2,
        closeBtn: 1,
        shadeClose: true,
        maxmin: true,
        offset: 'l',
        shade:0,
        title: [title, 'font-size:14px; font-weight:bold'],
        content: url,
        end:function () {
            mapObj.trailSource.clear();
            mapObj.bkSource.clear();
        }
    })
}

var sendLayer;

var sendMessage = function (ships,title) {
    if(typeof ships == "array"){
        ships = ships.join()
    }
    if(title == null){
        title = "发送消息";
    }
    var url = basePath+'/manage/map/message?ships='+ships ;
    if(company){
        url = basePath+'/manage/map/company/message?ships='+ships
    }
    sendLayer=layer.open({
        type: 2,
        title: title,
        shadeClose: true,
        shade: 0,
        maxmin: true,
        area: ['400px', '300px'],
        content:url, //iframe的url
    });
}
function serialize(feature) {
    try {
        var pretty = true;
        var str = new ol.format.WKT().writeFeature(feature, pretty).replace(/,/g, ', '); //formats['out'][type].write(feature, pretty);
        return str;
    } catch (e) {
        return "";
    }

}

function serialize1(feature) {
    
    try {
        var pretty = true;
        var str = new ol.format.WKT().writeFeature(feature, {
            dataProjection:'EPSG:4326',
            featureProjection:'EPSG:3857'
        }).replace(/,/g, ', '); //formats['out'][type].write(feature, pretty);
        return str;
    } catch (e) {
        return "";
    }

}


function shipway(chk) {
    if(chk.checked){
        document.getElementById("lat").style.display = "none";
        document.getElementById("lon").style.display = "none";
        document.getElementById("shipmmsi").style.display = "block";
    }
}

function show1(chk) {
    if(chk.checked){
        document.getElementById("lat").style.display = "block";
        document.getElementById("lon").style.display = "block";
        document.getElementById("shipmmsi").style.display = "none";
    }

}




function hidePop(mapObj) {
    mapObj.overlay.setPosition(undefined);
}
/**
 * 显示报告线
 * @param lineId 报告线ID
 */
var setLine = function(lineId){
    showReportLine(lineId);
}

var showReportLine = function (id) {
    var ff = new ol.format.WKT();;
    $.ajax({
        url: "/manage/reportline/info/one",
        data: {id:id},
        dataType: "json",
        success: function (data) {
            var ffs = [];
            var fid =  reportLineSource.getFeatureById(data.id);
            if(fid==null){
                var f = ff.readFeature(data.coordinate,{
                    dataProjection: 'EPSG:4326',
                    featureProjection: 'EPSG:3857'
                });
                var pp = data;
                f.setProperties(pp);
                f.setId(pp.id);
                ffs.push(f);
                reportLineSource.addFeatures(ffs);
            }
        }
    })
}


/**
 * 显示水域信息
 * @param id
 */
var setPolygon = function(data){
    getWatersinfo(data);
}

var  getWatersinfo = function (id) {
    var ff = new ol.format.WKT();
    $.ajax({
        url: "/manage/waters/info/getWkt",
        data: {id:id},
        dataType: "json",
        success: function (data) {
            var ffs = [];
            var fid =  waterSource.getFeatureById(data.id);
            if(fid==null){
                var f = ff.readFeature(data.coordinate,{
                    dataProjection: 'EPSG:4326',
                    featureProjection: 'EPSG:3857'
                });
                var pp = data;
                f.setProperties(pp);
                f.setId(pp.id);
                waterSource.addFeature(f);
            }
        }
    })
}

/**
 * 删除水域信息
 * @param id
 */
var romoveFeature = function(id){
    var fid =  waterSource.getFeatureById(id);
    if(fid)
    {
        waterSource.removeFeature(fid);
    }

}


var removeReport = function(id){
    var fid =  reportLineSource.getFeatureById(id);

    if(fid)
    {
        reportLineSource.removeFeature(fid);
    }
}



var showVtsInfo =function(id){
    findVts(id);
}

var findVts = function(guid){
    var ff = new ol.format.WKT();
    $.ajax({
        url: "/manage/map/oneVTS",
        data: {guid:guid},
        dataType: "json",
        success: function (data) {
            var ffs = [];
            var fid =  vtsSource.getFeatureById(data.Guid);
            if(fid==null){
    
                var f = ff.readFeature(data.Geom,{
                    dataProjection: 'EPSG:4326',
                    featureProjection: 'EPSG:3857'
                });
                var pp = data;
                f.setProperties(pp);
                f.setId(pp.Guid);
                f.set('source','vts');
                ffs.push(f);
                vtsSource.addFeatures(ffs);
            }
        }
    })
}

var refreshAll = function(guid){
    var fid = vtsSource.getFeatureById(guid);
    if(fid)
    {
        vtsSource.removeFeature(fid);
    }
    getVtsFeature();
}
// var editFeature = function (feature) {
//     if (!company) {
//         var ft = feature.geometry.CLASS_NAME.split('.')[2];
//         var info = "<tr><td class='tdl'>标题</td><td class='tdr'><input style='width:300px;' id='txtTitle' type='text' /></td><tr>";
//         info += " </tr><td class='tdl'>内容</td><td class='tdr'><textarea style='width:300px;' id='txtContent' rows='5' ></textarea></td></tr>";
//         info += " </tr><td class='tdl'>触发事件</td><td class='tdr'><select id='_event'><option value='1'>靠近</option>" + (ft == "Polygon" ? "<option value='2'>进入</option>" : "") + "</select></td></tr>";
//         var guid = "";
//         var btn = ['保存', '取消'];
//         if (feature.properties && feature.properties.guid) {
//             guid = feature.properties.guid;
//             btn = ['保存', '取消', '删除'];
//         }
//     } else {
//         var ss = "";
//         ss = type();
//         var ft = feature.geometry.CLASS_NAME.split('.')[2];
//         var info = "<tr><td class='tdl'>服务类型</td><td class='tdr'><select name='selectserver' id='selectserver'>" +
//             ss +
//             "</select></td><tr>" ;
//         info += "</tr><td class='tdl'>服务方式</td><td class='tdr'><input name='way' id='baseway' type='radio' checked='checked' value='地点' onclick='show1(this)'/>地点<input name='way' id='shipway' type='radio' value='船舶' onclick='shipway(this)'/>船舶</td><br>"
//         info += "</tr><td class='tdl'>请输入</td><td class='tdr'><input type='text' style='display: none;width:100px;' id='shipmmsi' placeholder='MMSI' ><input type='text' style='width:100px;' id='lon' placeholder='经度'><input type='text' style='width:100px;float: left' id='lat' placeholder='纬度'></td> "
//         info += "</tr><td class='tdl'>关键字</td><td class='tdr'><input style='width:300px;' id='keyword' type='text' placeholder='逗号隔开，最多五个字符，最多三个'/></td>"
//         info += "</tr><td class='tdl'>服务内容</td><td class='tdr'><textarea style='width:300px;' id='txtContent' rows='5' ></textarea></td></tr>";
//         var ssid = "";
//         var btn = ['发布', '取消'];
//         if (feature.properties && feature.properties.ssid) {
//             ssid = feature.properties.ssid;
//             btn = ['发布', '取消', '删除'];
//         }
//
//     }if(!company){
//         var ml = layer.open({
//             id: 'addWarn',
//             area: ['450px'],
//             type: 1,
//             closeBtn: 0,
//             title: ["保存警告", 'font-size:18px; font-weight:bold'],
//             content: "<table class='detail'>" + info + "</table>",
//             btn: btn,
//             success: function () {
//                 if (guid && guid != "") {
//
//                     $("#txtTitle").val(feature.properties.title);
//                     $("#txtContent").val(feature.properties.contents);
//                     $("#_event").val(feature.properties.event);
//
//                 }
//             },
//             yes: function (index) {
//
//                 var title = $("#txtTitle").val();
//                 var content = $("#txtContent").val();
//                 var _event = $("#_event").val();
//                 if (title == "" || content == "") {
//                     layer.msg("标题和内容不能为空");
//                 }
//                 else {
//                     var prop = {
//                         guid: guid,
//                         title: title,
//                         contents: content,
//                         wkt: serialize(feature),
//                         warningtype: ft,
//                         event: _event,
//                         mark: ""
//                     }
//                     feature.properties = prop;
//                     $.ajax({
//                         type: "POST",
//                         url: "/manage/map/navigat/warning/save",
//                         data: prop,
//                         dataType: "json",
//                         success: function (data) {
//                             if (data.result == true) {
//                                 feature.properties.guid = data.guid;
//                                 feature.id = data.guid;
//                                 layer.close(ml);
//                                 layer.msg("保存成功");
//                                 select.unselect(feature);
//                             }
//                             else {
//                                 layer.msg("保存失败");
//                             }
//                         },
//                         error: function (XMLHttpRequest, textStatus, errorThrown) {
//                             console.log(errorThrown);
//                         }
//                     });
//                 }
//             },
//             btn2: function (index) {
//                 if (guid == "") {
//                     vector.removeFeatures(feature);
//                 }
//                 else {
//                     select.unselect(feature);
//                 }
//             },
//             btn3: function (index) {
//                 select.unselect(feature);
//                 layer.confirm('确定删除?', {icon: 3, title: '提示'}, function (index) {
//                     $.ajax({
//                         type: "POST",
//                         url: "/manage/map/navigat/warning/delete",
//                         data: {guid: guid, action: "d"},
//                         dataType: "json",
//                         success: function (data) {
//                             if (data.result == true) {
//                                 vector.removeFeatures(feature);
//                                 layer.msg("删除成功");
//                                 layer.close(ml);
//
//                             }
//                             else {
//                                 layer.msg("保存失败");
//                             }
//                         },
//                         error: function (XMLHttpRequest, textStatus, errorThrown) {
//                             console.log(errorThrown);
//                         }
//                     });
//                 });
//             }
//         })}else {
//         var ml = layer.open({
//
//             id: 'addServer',
//             area: ['450px'],
//             type: 1,
//             closeBtn: 0,
//             title: ["服务信息", 'font-size:18px; font-weight:bold'],
//             content: "<table class='detail'>" + info + "</table>",
//             btn: btn,
//             success: function () {
//                 if (ssid && ssid != "") {
//                     //alert($("#selectserver").val(3));
//                     var rr = (feature.properties.serverway).toString();
//                     var ss = (feature.properties.serverType).toString();
//                     //alert(ss);
//                     if(rr == "地点"){
//                         document.getElementById("lat").style.display = "block";
//                         document.getElementById("lon").style.display = "block";
//                         document.getElementById("shipmmsi").style.display = "none";
//                     }else if(rr == "船舶"){
//                         document.getElementById("lat").style.display = "none";
//                         document.getElementById("lon").style.display = "none";
//                         document.getElementById("shipmmsi").style.display = "block";
//                     }
//                     $("#selectserver option:contains('"+ss+"')").attr("selected", true);
//                     $("#selectserver").find("option[text=ss]").attr("selected",true);
//                     $("input[name='way'][value='"+rr+"']").attr("checked",true);
//                     $("#keyword").val(feature.properties.keyword);
//                     $("#txtContent").val(feature.properties.message);
//                     $("#lon").val(feature.properties.lon);
//                     $("#lat").val(feature.properties.lat);
//                     $("#shipmmsi").val(feature.properties.mmsi);
//
//                 }
//             },
//             yes: function (index) {
//
//                 var serverType = $("#selectserver").find("option:selected").text();
//                 var keyword = $("#keyword").val();
//                 var message = $("#txtContent").val();
//                 var serverway = $("input[name='way']:checked").val();
//                 var lon = $("#lon").val();
//                 var lat = $("#lat").val();
//                 var mmsi = $("#shipmmsi").val();
//                 if (serverType == "" || message == "" || serverType == "==请选择==") {
//                     layer.msg("类型和内容不能为空");
//                 }else{
//                     var prop = {
//                         ssid:ssid,
//                         serverType: serverType,
//                         wkt: serialize(feature),
//                         keyword:keyword,
//                         message: message,
//                         serverway:serverway,
//                         lon:lon,
//                         lat:lat,
//                         mmsi:mmsi,
//                     }
//                     feature.properties = prop;
//                     $.ajax({
//                         type: "POST",
//                         url: "/manage/map/server/saveserver",
//                         data: prop,
//                         dataType: "json",
//                         success: function (data) {
//                             //alert("zzz");
//                             if (data.result == true) {
//                                 feature.properties.ssid = data.ssid;
//                                 feature.id = data.ssid;
//                                 layer.close(ml);
//                                 layer.msg("发布成功");
//                                 select.unselect(feature);
//                             }
//                             else if(data.keyword == false){
//                                 layer.msg("关键字过长");
//                             }else if(data.mmsi == false){
//                                 layer.msg("无效的mmsi");
//                             }else if(data.latlon == false){
//                                 layer.msg("经纬度不可为空");
//                             }
//                             else {
//                                 layer.msg("发布失败");
//                             }
//                         },
//                         error: function (XMLHttpRequest, textStatus, errorThrown) {
//                             console.log(errorThrown);
//                         }
//                     });
//                 }
//             },
//             btn2: function (index) {
//                 if (ssid == "") {
//                     vector.removeFeatures(feature);
//                 }
//                 else {
//                     select.unselect(feature);
//                 }
//             },
//             btn3: function (index) {
//                 select.unselect(feature);
//                 layer.confirm('确定删除?', {icon: 3, title: '提示'}, function (index) {
//                     $.ajax({
//                         type: "POST",
//                         url: "/manage/map/server/delete",
//                         data: {ssid: ssid, action: "d"},
//                         dataType: "json",
//                         success: function (data) {
//                             if (data.result == true) {
//                                 vector.removeFeatures(feature);
//                                 layer.msg("删除成功");
//                                 layer.close(ml);
//                             }
//                             else {
//                                 layer.msg("发布失败");
//                             }
//                         },
//                         error: function (XMLHttpRequest, textStatus, errorThrown) {
//                             console.log(errorThrown);
//                         }
//                     });
//                 });
//             }
//         })
//     }
//
// }
